<?php

require_once("LoginView.php");
require_once("LoginHandler.php");

class LoginController{
	
	/**
	 * Controls if you've tried to log in
	 * Logs you in
	 * Also checks if you've chosen the "remember me" option.
	 * @return DoLoginBox if the login fails or DoLogoutBox if it succeeds.
	 */
	public function DoControll(Database $db){
		
			$loginview = new LoginView();
			$loginhandler = new LoginHandler($db);

			
			if($loginhandler->IsLoggedIn())
			{
				
				if($loginview->TriedToLogOut())
				{
					$loginhandler->DoLogout();
					$loginview->LogOut();
					return $loginview->DoLoginBox() . $loginview->Messages(LoginView::LOGGED_OUT);
				}
				
				return $loginview->DoLogoutBox() . $loginview->Messages(LoginView::LOGGED_IN);
			}
			else 
			{
				
				if($loginview->DidRememberme() || $loginview->TriedToLogIn())
				{
				
					if($loginhandler->DoLogin($loginview->GetUserName(), $loginview->GetPassword()))
					{
						if($loginview->TickedRememberMe())
						{
							$loginview->RememberMe();
						}
					}
					else 
					{
						return $loginview->DoLoginBox() . $loginview->Messages(LoginView::WRONG_USER_OR_PASS);
					}
					
					if($loginhandler->IsLoggedIn())
					{
						return $loginview->DoLogoutBox() . $loginview->Messages(LoginView::LOGGED_IN);
					}
					else
					{
					return $loginview->DoLoginBox() . $loginview->Messages(LoginView::USER_NOT_LOGGED_IN);
					}
					
				}
				return $loginview->DoLoginBox();
			}
	}
	
}

?>